package com.plumejob.executor.util;

import com.plumejob.executor.PlumeJobDetail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.util.Date;


/**
 * @author Frank.chen
 */
public class TaskUtils {
    public final static Logger log = LoggerFactory.getLogger(TaskUtils.class);

    public static boolean invokMethod(PlumeJobDetail job) {
        job.setLastFireTime(new Date());
        job.setNextFireTime(job.getCronTrigger().getNextFireTime());
        Object object = null;
        Class clazz = null;
        if (!isEmpty(job.getJobClass())) {
            try {
                clazz = Class.forName(job.getJobClass());
                object = clazz.newInstance();
            } catch (Exception e) {
                error(job, LogExceptionStackTrace.erroStackTrace(e).toString());
                log.error("任务名称 = [" + job.getJobName() + "]未启动成功，初始化失败！！！", e);
                return false;
            }
        }
        if (object == null) {
            error(job, "未找到需要执行的类");
            log.error("任务名称 = [" + job.getJobName() + "]未启动成功，请检查是否配置正确！！！");
            return false;
        }
        clazz = object.getClass();
        Method method = null;
        try {
            if (isEmpty(job.getExtraData())) {
                method = clazz.getDeclaredMethod(job.getJobMethod());
            } else {
                method = clazz.getDeclaredMethod(job.getJobMethod(), String.class);
            }

        } catch (Exception e){
            error(job, LogExceptionStackTrace.erroStackTrace(e).toString());
            log.error("任务名称 = [" + job.getJobName() + "]未启动成功，初始化失败！！！", e);
            return false;
        }
        if (method != null) {
            try {
                if (isEmpty(job.getExtraData())) {
                    method.invoke(object);
                } else {
                    method.invoke(object, new Object[]{job.getExtraData()});
                }
                job.setLastEndTime(new Date());
                job.setResult(1);
            } catch (Exception e) {
                error(job, LogExceptionStackTrace.erroStackTrace(e).toString());
                log.error("任务名称 = [" + job.getJobName() + "]执行失败！！！", e);
                return false;
            }
        }
        return true;
    }

    private static void error(PlumeJobDetail job, String error) {
        job.setErrorMsg(error);
        job.setLastEndTime(new Date());
        job.setResult(-1);
    }

    private static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

}
